<script setup lang="ts">
// 定义组件名
defineOptions({ name: "CountryProfitChart" });
// /api/admin/profits/countries/stats
import { useDark, useECharts } from "@pureadmin/utils";
import { ref, watch, nextTick, computed, type PropType } from "vue";
import { generatePalette } from "@/plugins/echarts";

// TS 类型定义
interface TimeStat {
  period: string;
  cost: number;
  profit: number;
  sales: number;
  tasks: number;
}
interface CountryProfitItem {
  country: string;
  totalProfit: number;
  timeStats: TimeStat[];
  totalSales: number;
  totalTasks: number;
  totalCost: number;
}

// 组件接收数据为数组，每个对象为一国家的统计信息
const props = defineProps({
  data: {
    type: Array as PropType<CountryProfitItem[]>,
    default: () => []
  }
});

// ECharts 初始化
const chartRef = ref<HTMLDivElement>();
const { isDark } = useDark();
const themeName = "lowSaturationFancy";
const { setOptions } = useECharts(chartRef, { theme: themeName });

// 排序并提取分类与数值
const sorted = computed(() =>
  [...props.data].sort((a, b) => b.totalProfit - a.totalProfit)
);
const categories = computed(() => sorted.value.map(item => item.country));
const profits = computed(() => sorted.value.map(item => item.totalProfit));

// 监听变化并渲染
watch(
  () => props.data,
  async list => {
    await nextTick();

    const names = categories.value;
    const values = profits.value;
    const colors = generatePalette(values.length);

    // 垂直柱状图
    const barOption = {
      color: colors,
      tooltip: { trigger: "axis", axisPointer: { type: "shadow" } },
      grid: {
        left: "60px",
        right: "20px",
        top: "0px",
        bottom: "50px",
        containLabel: true
      },
      xAxis: {
        type: "category",
        data: names,
        axisLabel: { rotate: 30, color: isDark.value ? "#fff" : "#666" }
      },
      yAxis: {
        type: "value",
        axisLabel: { color: isDark.value ? "#fff" : "#666" },
        splitLine: { show: false }
      },
      series: [
        {
          type: "bar",
          name: "总收益",
          barWidth: "30%",
          itemStyle: { borderRadius: [4, 4, 0, 0] },
          label: { show: true, position: "top", formatter: "{c}" },
          data: values
        }
      ]
    };

    // 矩形树图（Treemap），展示各国收益占比
    const treemapOption = {
      tooltip: { trigger: "item", formatter: "{b}: {c}" },
      series: [
        {
          name: "国家收益占比",
          type: "treemap",
          roam: false,
          label: { show: true, formatter: "{b}\n{c}", color: "#fff" },
          itemStyle: { borderColor: "#fff", borderWidth: 2 },
          upperLabel: { show: false },
          data: sorted.value.map((item, index) => ({
            name: item.country,
            value: item.totalProfit,
            itemStyle: { color: colors[index] }
          }))
        }
      ]
    };

    // 默认渲染柱状图，如需矩形树图可切换：
    // setOptions(barOption);
    setOptions(treemapOption);
  },
  { immediate: true, deep: true }
);
</script>

<template>
  <div ref="chartRef" style="width: 100%; height: 365px" />
</template>
